<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>WebRTC capture video and audio</title>
  <style>

  </style>
</head>
<body>

<div>
  <label for="audioSource">audio Source</label>
  <select id="audioSource"></select>
</div>
<div>
  <label for="audioOutput">audio Output</label>
  <select id="audioOutput"></select>
</div>
<div>
  <label for="videoSource">video Source</label>
  <select id="videoSource"></select>
</div>

<div>
  <!--
    controls: 会显示暂停播放按钮
  -->
  <audio controls autoplay id="audioplayer"></audio>

  <!--<video autoplay playsinline id="player"></video>-->
</div>

<!--https://webrtc.github.io/adapter/adapter-latest.js-->
<!--https://webrtchacks.github.io/adapter/adapter-latest.js-->
<!--https://github.com/webrtchacks/adapter-->
<!--https://www.npmjs.com/package/webrtc-adapter-->
<script src="https://webrtc.github.io/adapter/adapter-latest.js"></script>
<script>
  // const audioSource = document.querySelector('select#audioSource'); //设置为id 已经自动获取
  // const audioOutput = document.querySelector('select#audioOutput');
  // const videoSource = document.querySelector('select#videoSource');

  start();

  videoSource.onchange = start;

  function start(){
    if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
      console.log('getUserMedia is not supported!');
    }else {
      const deviceId = videoSource.value;

      const MediaStreamConstrains = {
        video: false,
        audio: {
          echoCancellation: false, //todo 设置为true会有啸叫
          noiseSuppression: true
        }
      };

      navigator.mediaDevices.getUserMedia(MediaStreamConstrains)
        .then(gotMediaStream)
        .then(gotDevices)
        .catch(handleError);
    }
  }


  function gotMediaStream(stream){
    audioplayer.srcObject = stream;
    return navigator.mediaDevices.enumerateDevices();
  }

  function handleError(error){
    console.error('getUserMedia error:', error);
  }

  let hasSet = false;
  function gotDevices(deviceInfos) {
    if(hasSet) return;
    hasSet = true;
    deviceInfos.forEach((deviceInfo) => {
      const option = document.createElement('option');
      option.text = deviceInfo.label;
      option.value = deviceInfo.deviceId;
      switch (deviceInfo.kind) {
        case 'audioinput':
          audioSource.appendChild(option);
          break;
        case 'audiooutput':
          audioOutput.appendChild(option);
          break;
        case 'videoinput':
          videoSource.appendChild(option);
      }
    });
  }

</script>
</body>
</html>
